import axios from 'axios'
import qs from 'qs'
import { MessageBox, Message } from 'element-ui'
import router from '@/router'
// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: hostSetting.host,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor  拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (localStorage.getItem('bf-admin-token')) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // http对象的组成
      // 1. url地址栏  比如get提交的数据 ?key=v&key-v
      // 2. 请求头  xxx:xxx
      // 3. 请求体  比如post提交的数据
      config.headers['bufan-token'] = localStorage.getItem('bf-admin-token')
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (res.tokenCode == 5000 || res.tokenCode == 5001) {
      Message({
        message: '未登录或登陆失效,请重新登陆!',
        type: 'error',
        duration: 5 * 1000
      })
      // 清除非法token
      localStorage.removeItem('bf-admin-token')
      localStorage.removeItem('bf-admin-user')
      // 跳转到首页
      router.push('/login')
    }
    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
// http({
//   url: 'http://bufantec.com/admin/xy/clazz/save',
//   method: 'post',
//   params
// })
// 用于对service进行再次包装
function http(config) {
  // axios的默认配置 如果时get 参数需要放到 params
  // 如果是post 参数需要放到  data
  var myConfig = {
    url: config.url,
    method: config.method
  }

  if (config.method.toLowerCase() == 'post') {
    // 对数据进行序列化
    //  https://www.npmjs.com/package/qs
    // qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true });  ===>  'a.b.c=d&a.b.e=f'
    myConfig.data = qs.stringify(config.params, { allowDots: true, arrayFormat: 'repeat' })
  } else if (config.method.toLowerCase() == 'get') {
    myConfig.params = config.params
  }

  // 区分了get和post 的配置
  return service(myConfig)
}

export default http
